//
//  T3FColorUtil.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/11/13.
//

import Foundation

struct T3FColorUtil {

    static func hex(_ hex:String, alpha: Double = 1.0) -> UIColor {
        var red: CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue: CGFloat = 0.0
        var value = hex
        var nAlpha = alpha
        if hex.hasPrefix("#") {
            let index = hex.index(hex.startIndex, offsetBy: 1)
            value = String(hex[index...])
        }

        let scanner = Scanner(string: value)
        var hexValue: CUnsignedLongLong = 0
        if scanner.scanHexInt64(&hexValue) {
            switch value.count {
            case 3:
                red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
                green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
                blue = CGFloat(hexValue & 0x00F) / 15.0
            case 4:
                red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
                green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
                blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
                nAlpha = CGFloat(hexValue & 0x000F) / 15.0
            case 6:
                red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
                blue = CGFloat(hexValue & 0x0000FF) / 255.0
            case 8:
                red = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                green = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
                blue = CGFloat(hexValue & 0x000000FF) / 255.0
                nAlpha = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
            default:
                break
            }
        }
        return UIColor(red: red, green: green, blue: blue, alpha: nAlpha)
    }
}
